import { Component, OnInit, HostBinding, ChangeDetectorRef, TemplateRef, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
import { RegExs } from 'app/modules/base/regex';
import { confirmPassword, markAllAsTouched } from 'app/modules/base/helper';
import { AuthenticationService } from '../../../../core/auth/authentication.service';
import { ProfileService } from '../../../../services/profile.service';
import { take, map, finalize } from 'rxjs/operators';
import { timer } from 'rxjs';
import { MatDialog } from '@angular/material';

@Component({
  selector: 'm-reset-password-ldap',
  templateUrl: './reset-password.component.html',
  styleUrls: ['./reset-password.component.scss']
})
export class ResetPasswordComponent implements OnInit {

  profile$ = this.profileService.profile$;
  sendCaptcha = false;
  interval$;
  countDownNum = 60;

  constructor(
    private fb: FormBuilder,
    private profileService: ProfileService,
    private cdRef:ChangeDetectorRef,
    public dialog: MatDialog,

    ) {

   }

  @HostBinding('class') classList = 'm-grid m-grid--hor m-grid--root m-page ng-star-inserted';
  @ViewChild('alertRef') alertRef: TemplateRef<any>;

  form = this.fb.group({
    mobileno: new FormControl('', Validators.compose([
                Validators.required,
                Validators.pattern(RegExs.PHONE),
                ]) ),
    captcha: ['', Validators.required],
    password: ['', Validators.compose([
      Validators.required,
      Validators.pattern(RegExs.PASSWORD),
    ])],
    password_confirm: ['', Validators.required],
  }, {
    validators: confirmPassword({
      password: 'password',
      confirm: 'password_confirm'
    })
  });

  async onSendClick() {
    try {
      const mobileno = this.form.controls['mobileno'].value;
      const res = await this.profileService.receiveCaptcha(mobileno);
      this.toggleButton();
    } catch (error) {
      this.form.setErrors({ captcha: true, message: error.error });
      this.cdRef.detectChanges();
    }
	}
  ngOnInit() {
    this.profile$.then(profile => {
      document.title = profile.name;
    });
    this.dialog.afterAllClosed.subscribe(() => {
      this.form.reset();
    })
  }

  async onSubmit() {
    markAllAsTouched(this.form);
    if (!this.form.invalid) {
      await this.profileService.resetPassword({
        phone: this.form.get('mobileno').value,
        code: this.form.get('captcha').value,
        ldap_password: this.form.get('password').value,
      });
      this.dialog.open(this.alertRef, { width: '30rem' });
    }
    this.cdRef.detectChanges();
  }

  toggleButton() {
    this.sendCaptcha = !this.sendCaptcha;
    this.interval$ = timer(0, 1000).pipe(
      map(v => {
        return this.countDownNum - v
      }),
      take(this.countDownNum),
      finalize(() => {
        this.sendCaptcha = !this.sendCaptcha;
      })
    )
    this.cdRef.detectChanges();
  }
}
